package com.zisuyi.uilibrary.module.activty.redeem

import android.widget.EditText
import com.weilele.mvvm.base.helper.*
import com.weilele.mvvm.utils.activity.toast
import com.zisuyi.game.sdk.net.GameModel
import com.zisuyi.game.sdk.net.bean.RedeemBean
import com.zisuyi.game.sdk.net.bean.RedeemHistoryBean
import com.zisuyi.game.sdk.net.bean.UserInfoBean
import com.zisuyi.game.sdk.net.bean.req.RedeemReq
import com.zisuyi.uilibrary.base.BaseUiViewModel
import java.lang.IllegalArgumentException

class RedeemViewModel : BaseUiViewModel() {
    /**
     * 兑换提交
     */
    val redeemData = createStatusLiveData<RedeemBean>()
    fun redeem(emailEt: EditText?, emailAgainEt: EditText?, redeemDTO: UserInfoBean.RedeemDTO?) {
        redeemDTO ?: return
        val email = emailEt?.text?.toString()
        val emailAgain = emailAgainEt?.text?.toString()
        if (email.isNullOrBlank()) {
            "please input your email".toast()
            return
        }
        if (emailAgain.isNullOrBlank()) {
            "please input your email again".toast()
            return
        }
        if (email != emailAgain) {
            "The two mailbox entries are inconsistent".toast()
            return
        }
        redeemData.retrofitGame {
            GameModel.redeem(RedeemReq(email, redeemDTO.id, null))
        }
    }

    /**
     * 兑换历史
     */
    private val _redeemHistoryData = createStatusListLiveData<RedeemHistoryBean>()

    val redeemHistoryData = createStatusListMediatorLiveData<RedeemHistoryBean>().apply {
        this.addSource(_redeemHistoryData) {
            when (it) {
                is StatusValue.Running -> {
                    this.running()
                }
                is StatusValue.Error -> {
                    this.error(it.nonNullMsg)
                }
                is StatusValue.Success -> {
                    val orders = it.nonNullValue
                    if (orders.isNullOrEmpty()) {
                        error("You haven’t redeem any gifts yet.\nGo to play games to get more coins!")
                    } else {
                        success(orders)
                    }
                }
            }
        }
    }

    fun redeemHistory() {
        _redeemHistoryData.retrofitGame(isToastError = false) {
            try {
             GameModel.redeemHistory()
            } catch (e: Throwable) {
                e.printStackTrace()
                throw IllegalArgumentException("You haven’t redeem any gifts yet.\nGo to play games to get more coins!")
            }
        }
    }

    /**
     * 获取兑换条件
     */
    val redeemConditionData by lazy { createStatusListLiveData<UserInfoBean.RedeemDTO.ConditionsDTO>() }
    fun redeemCondition() {
        redeemConditionData.retrofitGame {
            GameModel.redeemCondition()
        }
    }
}